<template>
  <div class="shop-view">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载店铺信息...</p>
    </div>

    <!-- 店铺内容 -->
    <template v-else>
      <div class="shop-header" :style="{ backgroundImage: `url(${shopInfo.headerImage})` }">
        <div class="overlay">
          <div class="back-btn" @click="goBack">
            <i class="arrow"></i>
          </div>
          <h2>{{ shopInfo.name }}</h2>
          <div class="shop-meta">
            <span>评分: {{ shopInfo.rating.toFixed(1) }} ★</span>
            <span>月售{{ shopInfo.monthlySales }}单</span>
            <span>配送费¥{{ shopInfo.deliveryFee }}</span>
          </div>
          <div v-if="shopInfo.description" class="shop-description">
            {{ shopInfo.description }}
          </div>
        </div>
      </div>

      <div class="shop-content">
        <div class="categories" v-if="categories.length > 0">
          <div 
            v-for="category in categories" 
            :key="category.id"
            :class="{ active: activeCategory === category.id }"
            @click="activeCategory = category.id"
          >
            {{ category.name }}
          </div>
        </div>

        <!-- 商品列表 -->
        <div v-if="filteredProducts.length > 0" class="products">
          <div v-for="product in filteredProducts" :key="product.id" class="product-card">
            <img :src="product.image" :alt="product.name" />
            <div class="product-info">
              <h4>{{ product.name }}</h4>
              <p class="desc">{{ product.description }}</p>
              <div class="price">¥{{ product.price }}</div>
            </div>
            <button class="add-btn" @click.stop="addToCart(product)">+</button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-products">
          <div class="empty-icon">🍽️</div>
          <p>该店铺暂无商品</p>
        </div>
      </div>

      <div class="cart-bar" :class="{ active: cartItems.length > 0 }">
        <div class="cart-icon" @click="showCart = true">
          <i class="cart-icon-inner"></i>
          <span class="cart-count" v-if="totalItems > 0">{{ totalItems }}</span>
        </div>
        <div class="cart-info">
          <div class="total-price">¥{{ totalPrice.toFixed(2) }}</div>
          <div class="delivery-fee">配送费¥{{ shopInfo.deliveryFee }}</div>
        </div>
        <button class="checkout-btn" @click="goToCheckout" :disabled="cartItems.length === 0">
          去结算
        </button>
      </div>

      <div v-if="showCart" class="cart-modal">
        <div class="modal-header">
          <h3>购物车</h3>
          <button class="clear-btn" @click="clearCart">清空</button>
        </div>
        <div class="cart-items">
          <div v-for="(item, index) in cartItems" :key="index" class="cart-item">
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <div class="price">¥{{ item.price.toFixed(2) }}</div>
            </div>
            <div class="item-controls">
              <button @click="updateQuantity(item, -1)">-</button>
              <span>{{ item.quantity }}</span>
              <button @click="updateQuantity(item, 1)">+</button>
            </div>
          </div>
        </div>
        <button class="close-btn" @click="showCart = false">关闭</button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  selectById as getShopById,
  type Shop as ApiShop 
} from '@/http/Shop';
import { 
  selectAll as getAllGoods,
  selectEq as getGoodsByCondition,
  type Goods as ApiGoods,
  type PageInfo 
} from '@/http/Goods';
import { 
  selectAll as getAllCategories,
  selectEq as getCategoriesByCondition,
  type GoodsCategory as ApiGoodsCategory 
} from '@/http/GoodsCategory';
import { message } from '@/utils/message';

interface Product {
  id: number;
  name: string;
  price: number;
  description: string;
  image: string;
  categoryId: number;
}

interface CartItem extends Product {
  quantity: number;
}

interface Category {
  id: number;
  name: string;
}

interface ShopInfo {
  id: number;
  name: string;
  headerImage: string;
  rating: number;
  monthlySales: number;
  deliveryFee: number;
  description?: string;
  address?: string;
  phone?: string;
}

const route = useRoute();
const router = useRouter();
const shopId = parseInt(route.params.id as string);

// 响应式数据
const loading = ref(true);
const shopInfo = ref<ShopInfo>({
  id: shopId,
  name: '加载中...',
  headerImage: '/default-shop.jpg',
  rating: 4.5,
  monthlySales: 0,
  deliveryFee: 0
});

// 原静态数据（保留备用）
// const staticShopInfo = ref({
//   id: shopId,
//   name: '香辣小龙虾',
//   headerImage: '/shop001.jpg',
//   rating: 4.8,
//   monthlySales: 1240,
//   deliveryFee: 3
// });

const categories = ref<Category[]>([]);
const products = ref<Product[]>([]);

// 原静态数据（保留备用）
// const staticCategories = ref<Category[]>([
//   { id: 1, name: '热销推荐' },
//   { id: 2, name: '小龙虾系列' },
//   { id: 3, name: '烧烤串串' },
//   { id: 4, name: '凉菜小食' },
//   { id: 5, name: '酒水饮料' }
// ]);

// const staticProducts = ref<Product[]>([
//   { id: 1, name: '麻辣小龙虾', price: 98, description: '招牌麻辣口味，鲜香过瘾', image: '/food001.jpg', categoryId: 1 },
//   { id: 2, name: '蒜蓉小龙虾', price: 98, description: '蒜香浓郁，肉质鲜嫩', image: '/food009.jpg', categoryId: 1 },
//   { id: 3, name: '十三香小龙虾', price: 108, description: '秘制香料，回味无穷', image: '/food010.jpg', categoryId: 2 },
//   { id: 4, name: '烤羊肉串', price: 5, description: '新鲜羊肉，炭火烤制', image: '/food006.jpg', categoryId: 3 },
//   { id: 5, name: '冰镇酸梅汤', price: 12, description: '解腻解辣，冰爽可口', image: '/food007.jpg', categoryId: 5 }
// ]);

const activeCategory = ref(0); // 默认显示所有商品
const cartItems = ref<CartItem[]>([]);
const showCart = ref(false);

// 将后端Shop数据转换为前端显示格式
const convertApiShopToDisplay = (apiShop: ApiShop): ShopInfo => {
  return {
    id: apiShop.id || 0,
    name: apiShop.name || '未命名店铺',
    headerImage: apiShop.image || '/default-shop.jpg',
    rating: apiShop.avRating || 4.5,
    monthlySales: apiShop.monthlyOrderCount || 0,
    deliveryFee: Math.round((apiShop.deliveryFee || 500) / 100), // 转换为元
    description: apiShop.description || undefined,
    address: apiShop.address || undefined,
    phone: apiShop.phone || undefined
  };
};

// 将后端Goods数据转换为前端显示格式
const convertApiGoodsToDisplay = (apiGoods: ApiGoods): Product => {
  return {
    id: apiGoods.id || 0,
    name: apiGoods.name || '未命名商品',
    price: Math.round((apiGoods.price || 1000) / 100), // 转换为元
    description: apiGoods.description || '暂无描述',
    image: apiGoods.imageAddress || '/default-food.jpg', // 使用API返回的图片地址
    categoryId: apiGoods.relaGoodsCategoryId || 0
  };
};

// 将后端GoodsCategory数据转换为前端显示格式
const convertApiCategoryToDisplay = (apiCategory: ApiGoodsCategory): Category => {
  return {
    id: apiCategory.id || 0,
    name: apiCategory.name || '未命名分类'
  };
};

// 加载店铺信息
const loadShopInfo = async () => {
  try {
    console.log('🏪 加载店铺信息:', shopId);
    
    const response = await getShopById(shopId);
    
    if (response.data) {
      shopInfo.value = convertApiShopToDisplay(response.data);
      console.log('✅ 店铺信息加载成功:', shopInfo.value);
    } else {
      console.log('⚠️ 店铺信息为空');
      message.warning('店铺信息不存在');
    }
  } catch (error: any) {
    console.error('❌ 加载店铺信息失败:', error);
    message.error(`加载店铺信息失败: ${error.message || '网络错误'}`);
    
    // 错误时使用静态数据作为备用
    // shopInfo.value = staticShopInfo.value;
  }
};

// 加载商品分类
const loadCategories = async () => {
  try {
    console.log('📂 加载商品分类...');
    console.log('🔗 请求URL: http://localhost:9001/goods-category/select-eq');
    
    // 尝试不同的参数格式
    const params1 = { relaShopId: shopId };
    const params2 = { rela_shop_id: shopId };
    
    console.log('📊 尝试参数格式1 (驼峰):', params1);
    console.log('📊 尝试参数格式2 (下划线):', params2);
    console.log('🏪 shopId类型:', typeof shopId, '值:', shopId);
    
    // 先尝试驼峰命名
    let response;
    try {
      response = await getCategoriesByCondition(params1);
      console.log('✅ 驼峰参数成功:', response);
    } catch (error1: any) {
      console.log('❌ 驼峰参数失败，尝试下划线参数:', error1.message);
      try {
        response = await getCategoriesByCondition(params2);
        console.log('✅ 下划线参数成功:', response);
      } catch (error2: any) {
        console.log('❌ 下划线参数也失败:', error2.message);
        throw error2;
      }
    }
    
    console.log('📥 分类API响应:', response);
    
    if (response.data && response.data.length > 0) {
      const convertedCategories = response.data.map(convertApiCategoryToDisplay);
      // 添加"全部"分类
      categories.value = [
        { id: 0, name: '全部' },
        ...convertedCategories
      ];
      console.log('✅ 商品分类加载成功:', categories.value);
    } else {
      console.log('⚠️ 没有商品分类数据');
      categories.value = [{ id: 0, name: '全部' }];
    }
  } catch (error: any) {
    console.error('❌ 加载商品分类失败:', error);
    console.error('🔍 错误详情:', {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      url: error.config?.url,
      method: error.config?.method,
      data: error.response?.data
    });
    message.error(`加载商品分类失败: ${error.message || '网络错误'}`);
    
    // 错误时使用静态数据作为备用
    // categories.value = staticCategories.value;
    categories.value = [{ id: 0, name: '全部' }];
  }
};

// 加载商品列表
const loadProducts = async () => {
  try {
    console.log('🍽️ 加载商品列表...');
    console.log('🔗 请求URL: http://localhost:9001/goods/select-eq');
    console.log('📊 请求参数:', { relaShopId: shopId });
    
    // 获取该店铺的商品
    const response = await getGoodsByCondition({
      relaShopId: shopId
    });
    
    console.log('📥 商品API响应:', response);
    
    if (response.data && response.data.length > 0) {
      products.value = response.data.map(convertApiGoodsToDisplay);
      console.log('✅ 商品列表加载成功:', products.value);
    } else {
      console.log('⚠️ 没有商品数据');
      message.info('该店铺暂无商品');
    }
  } catch (error: any) {
    console.error('❌ 加载商品列表失败:', error);
    console.error('🔍 错误详情:', {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      url: error.config?.url,
      method: error.config?.method
    });
    message.error(`加载商品列表失败: ${error.message || '网络错误'}`);
    
    // 错误时使用静态数据作为备用
    // products.value = staticProducts.value;
  }
};

// 加载所有数据
const loadAllData = async () => {
  loading.value = true;
  
  try {
    // 并行加载所有数据
    await Promise.all([
      loadShopInfo(),
      loadCategories(),
      loadProducts()
    ]);
  } catch (error) {
    console.error('❌ 加载数据失败:', error);
  } finally {
    loading.value = false;
  }
};

const filteredProducts = computed(() => {
  if (activeCategory.value === 0) {
    return products.value; // 显示所有商品
  }
  return products.value.filter(p => p.categoryId === activeCategory.value);
});

const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0);
});

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0);
});

const addToCart = (product: Product) => {
  const existingItem = cartItems.value.find(item => item.id === product.id);
  
  if (existingItem) {
    existingItem.quantity += 1;
  } else {
    cartItems.value.push({
      ...product,
      quantity: 1
    });
  }
  
  message.success(`已添加 ${product.name} 到购物车`);
};

const updateQuantity = (item: CartItem, change: number) => {
  const index = cartItems.value.findIndex(i => i.id === item.id);
  if (index !== -1) {
    cartItems.value[index].quantity += change;
    
    if (cartItems.value[index].quantity <= 0) {
      cartItems.value.splice(index, 1);
    }
  }
};

const clearCart = () => {
  cartItems.value = [];
  showCart.value = false;
  message.success('购物车已清空');
};

const goToCheckout = () => {
  if (cartItems.value.length > 0) {
    // 这里可以传递购物车数据到结算页面
    router.push({
      path: '/checkout',
      query: {
        shopId: shopId.toString(),
        items: JSON.stringify(cartItems.value)
      }
    });
  } else {
    message.warning('购物车为空');
  }
};

const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  document.body.classList.add('shop-view-active');
  
  // 验证shopId
  if (!shopId || isNaN(shopId)) {
    message.error('店铺ID无效');
    router.push('/square');
    return;
  }
  
  // 加载数据
  loadAllData();
});
</script>

<style scoped>
.shop-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f8f9fa;
}

.shop-header {
  height: 200px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.7));
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  color: white;
}

.back-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 36px;
  height: 36px;
  background: rgba(255,255,255,0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  backdrop-filter: blur(5px);
}

.arrow {
  width: 12px;
  height: 12px;
  border-left: 2px solid white;
  border-bottom: 2px solid white;
  transform: rotate(45deg);
  margin-right: 3px;
}

.shop-header h2 {
  margin: 0;
  font-size: 1.8rem;
}

.shop-meta {
  display: flex;
  gap: 15px;
  margin-top: 8px;
  font-size: 0.9rem;
  opacity: 0.9;
}

.shop-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.categories {
  width: 100px;
  background: white;
  overflow-y: auto;
  padding: 10px 0;
  box-shadow: 2px 0 5px rgba(0,0,0,0.05);
}

.categories div {
  padding: 14px 10px;
  text-align: center;
  font-size: 0.9rem;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}

.categories div.active {
  background: #fff9f8;
  color: #ff6b6b;
  font-weight: bold;
  border-left: 3px solid #ff6b6b;
}

.categories div:hover {
  background: #f8f9ff;
}

.products {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.product-card {
  display: flex;
  background: white;
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  position: relative;
}

.product-card img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 5px;
  color: #333;
}

.desc {
  color: #888;
  font-size: 0.85rem;
  margin: 0 0 8px;
  max-width: 80%;
}

.price {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 1.1rem;
}

.add-btn {
  position: absolute;
  bottom: 12px;
  right: 12px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  color: white;
  border: none;
  font-size: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(255,107,107,0.3);
}

.cart-bar {
  display: flex;
  align-items: center;
  background: white;
  padding: 12px 20px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
  transform: translateY(80px);
  transition: transform 0.3s;
}

.cart-bar.active {
  transform: translateY(0);
}

.cart-icon {
  position: relative;
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(255,107,107,0.3);
}

.cart-icon-inner {
  position: relative;
  width: 24px;
  height: 22px;
  border: 2px solid white;
  border-radius: 2px 2px 8px 8px;
}

.cart-icon-inner::before {
  content: '';
  position: absolute;
  width: 6px;
  height: 6px;
  border: 2px solid white;
  border-radius: 50%;
  top: -10px;
  left: 3px;
}

.cart-icon-inner::after {
  content: '';
  position: absolute;
  width: 6px;
  height: 6px;
  border: 2px solid white;
  border-radius: 50%;
  top: -10px;
  right: 3px;
}

.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4757;
  color: white;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7rem;
  font-weight: bold;
}

.cart-info {
  flex: 1;
  padding: 0 15px;
}

.total-price {
  font-weight: bold;
  font-size: 1.2rem;
  color: #ff6b6b;
}

.delivery-fee {
  font-size: 0.85rem;
  color: #888;
}

.checkout-btn {
  padding: 12px 30px;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  color: white;
  border: none;
  border-radius: 30px;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(255,107,107,0.3);
  transition: all 0.3s;
}

.checkout-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 15px rgba(255,107,107,0.4);
}

.cart-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 70vh;
  background: white;
  border-radius: 20px 20px 0 0;
  padding: 20px;
  box-shadow: 0 -5px 20px rgba(0,0,0,0.15);
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.clear-btn {
  background: none;
  border: none;
  color: #ff6b6b;
  font-size: 0.9rem;
  cursor: pointer;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 15px 0;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-info h4 {
  margin: 0 0 5px;
}

.item-info .price {
  color: #ff6b6b;
  font-weight: bold;
}

.item-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-controls button {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  border: 1px solid #ff6b6b;
  background: white;
  color: #ff6b6b;
  font-size: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.item-controls span {
  min-width: 25px;
  text-align: center;
}

.close-btn {
  margin-top: 15px;
  padding: 12px;
  background: #f0f2f5;
  border: none;
  border-radius: 8px;
  color: #333;
  font-weight: bold;
  cursor: pointer;
}

.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #ff6b6b;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.empty-products {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.empty-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.shop-description {
  margin-top: 10px;
  text-align: center;
  color: #888;
}
</style>